package com.example.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.medical.entity.dto.*;
import com.example.medical.entity.pojo.Division;
import com.example.medical.entity.pojo.Leadership;
import com.example.medical.entity.pojo.User;
import com.example.medical.mapper.DivisionMapper;
import com.example.medical.mapper.LeadershipMapper;
import com.example.medical.service.UserService;
import com.example.medical.mapper.UserMapper;
import com.example.medical.utils.common.enums.Code;
import com.example.medical.utils.common.enums.Jwt;
import com.example.medical.utils.common.enums.Message;
import com.example.medical.utils.common.result.PageResponseResult;
import com.example.medical.utils.common.result.Result;
import com.example.medical.utils.config.BaseContext;
import com.example.medical.utils.config.EverythingConfig;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;

/**
* @author 24354
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-31 22:42:32
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EverythingConfig everythingConfig;
    @Autowired
    private DivisionMapper divisionMapper;
    @Autowired
    private LeadershipMapper leadershipMapper;

    @Override
    public Result UserLogin(LoginDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        User checkUser = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, dto.getUsername()));
        if (checkUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String password=dto.getPassword();
        password= DigestUtils.md5Hex(password);
        if (!checkUser.getUserPassword().equals(password)) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        String id= String.valueOf(checkUser.getUserId());
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Alg, Jwt.User_Jwt_Key.getAlg())
                .setHeaderParam(Message.Jwt_Typ, Jwt.User_Jwt_Key.getTyp())
                .setSubject(Jwt.User_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis() + Jwt.User_Jwt_Key.getExp()))
                .claim(Message.User_Id,id )
                .signWith(SignatureAlgorithm.HS256, Jwt.User_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result SaveUser(SaveUserDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        if (!dto.getPassword().equals(dto.getPasswordCopy())) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        String password = DigestUtils.md5Hex(dto.getPassword());
        User user=new User();
        user= user.builder()
                .userName(dto.getUsername())
                .password(dto.getPassword())
                .userPassword(password)
                .userNick(dto.getNick())
                .userPhone(dto.getPhone())
                .userNumber(dto.getNumber())
                .userEmail(dto.getEmail()).build();
        int checkSave = userMapper.insert(user);
        if (checkSave==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result UpdateUserPassword(UpdatePasswordDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (checkUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        log.info("dto:{}",dto);
        if (!checkUser.getPassword().equals(dto.getOldPassword())) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        if (!dto.getNewPassword().equals(dto.getNewPasswordCopy())) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        User user=new User();
        user= user.builder()
                .userId(checkUser.getUserId())
                .password(dto.getNewPassword())
                .userPassword(DigestUtils.md5Hex(dto.getNewPassword())).build();
        boolean checkUpdate = updateById(user);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result UpdateUserDetail(MultipartFile file, Long divisionId, Integer sex) throws Exception {
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        if (checkUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Division checkDivision = divisionMapper.selectById(divisionId);
        if (checkDivision==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String url = everythingConfig.Upload(file);
        User user=new User();
        BeanUtils.copyProperties(checkUser,user);
        user.setUserImgUrl(url);
        if (divisionId!=null) {
            user.setUserDivisionId(divisionId);
            user.setUserDivisionName(checkDivision.getDivisionName());
        }
        if (sex!=null) {
            user.setUserSex(sex);
        }
        boolean checkUpdate = updateById(user);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result LeadershipGetUserList(LeadershipGetUserListDto dto) {
        Long adminId = BaseContext.getCurrentId();
        if (adminId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        dto.checkParam();
        IPage<User> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        if (dto.getSex()!=null) {
            wrapper.eq(User::getUserSex,dto.getSex());
        }
        if (dto.getDivisionId()!=null) {
            wrapper.eq(User::getUserDivisionId,dto.getDivisionId());
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            wrapper.like(User::getUserNick,dto.getName());
        }
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public Result AdminRemoveUserArr(String[] ids) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        for (String id : ids) {
            User checkUser = getById(id);
            if (checkUser==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            boolean checkRemove = removeById(id);
            if (!checkRemove) {
                return Result.errorResult(Code.SERVER_ERROR);
            }
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result AdminUpdateUserPassword(Long id) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        User checkUser = getById(id);
        if (checkUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        checkUser.setPassword("123456");
        checkUser.setUserPassword(DigestUtils.md5Hex("123456"));
        boolean checkUpdate = updateById(checkUser);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result AdminUpdateUser(Long id, String name, String nick, Long phone, Long number, MultipartFile file, Integer sex, String divisionId, String email) throws Exception {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        User checkUser = userMapper.selectById(id);
        if (checkUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (StringUtils.isNotBlank(name)) {
            checkUser.setUserName(name);
        }
        if (StringUtils.isNotBlank(nick)) {
            checkUser.setUserNick(nick);
        }
        if (phone!=null) {
            checkUser.setUserPhone(phone);
        }
        if (number!=null) {
            checkUser.setUserNumber(number);
        }
        if (file!=null&&file.getSize()>0) {
            String upload = everythingConfig.Upload(file);
            checkUser.setUserImgUrl(upload);
        }
        if (sex!=null) {
            checkUser.setUserSex(sex);
        }
        if (divisionId!=null) {
            Division checkDivision = divisionMapper.selectById(divisionId);
            if (checkDivision==null) {
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            checkUser.setUserDivisionId(checkDivision.getDivisionId());
            checkUser.setUserDivisionName(checkDivision.getDivisionName());
        }
        if (StringUtils.isNotBlank(email)) {
            checkUser.setUserEmail(email);
        }
        boolean checkUpdate = updateById(checkUser);
        if (!checkUpdate) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result AdminSaveUser(String name, String nick, Long phone, Long number, MultipartFile file, Integer sex, Long divisionId, String email) throws Exception {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Division checkDivision = divisionMapper.selectById(divisionId);
        if (checkDivision==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String upload = everythingConfig.Upload(file);
        User user=new User().builder()
                .userName(name)
                .password("123456")
                .userPassword(DigestUtils.md5Hex("123456"))
                .userNick(nick)
                .userPhone(phone)
                .userNumber(number)
                .userImgUrl(upload)
                .userSex(sex)
                .userDivisionId(checkDivision.getDivisionId())
                .userDivisionName(checkDivision.getDivisionName())
                .userEmail(email)
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean checkSave = save(user);
        if (!checkSave) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

}




